import React, {useEffect, useState} from 'react';
import ProForm, { ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import {Modal, message, Form, Input, Upload, Button, Avatar, Image, Select} from 'antd';
import {getAdminUserInfo, editAdminUser, addAdminUser, getAdminRoleList} from '@/services/rule';
import {UploadOutlined, UserOutlined} from '@ant-design/icons';
import styles from './index.less';

const Edit = (props) => {
  const {Option} = Select;

  const {isModalVisible, isShowModal, actionRef, editId} = props;
  const [roleList, setRoleList] = useState([]); // 地区数据
  // const [formData, setFormData] = useState([]); // 表单数据
  const [avatar, setAvatar] = useState();
  const [visible, setVisible] = useState(false);

  const [formLayout] = useState('horizontal');

  const title = editId === null ? '添加用户' : '编辑用户';

  const formItemLayout =
    formLayout === 'horizontal' ? {labelCol: {span: 4}, wrapperCol: {span: 20}} : null;

  useEffect(() => {
    getRoleList()
  }, [])

  /**
   * 获取数据
   * 作者：糜家智
   * 时间：2021/8/2 18:03
   */
  const getData = async () => {
    const res = await getAdminUserInfo({
      admin_user_id: editId,
    });
    setAvatar(res.data.avatar);
    return res.data;
  };

  const getRoleList = () => {
    getAdminRoleList({limit: 100}).then((res) => {
      // setRoleList(res.data.list  )
      setRoleList(res.data.list)
    })
  }

  /**
   * 作者：糜家智
   * 时间：2022/04/18 17:32:00
   * 功能：提交按钮
   */
  const handleSubmit = async (values) => {
    const data = values;
    let res = {};

    data.admin_role_ids = ',' + data.admin_role_ids.join(',') + ','

    if (editId === null) {
      res = await addAdminUser(data);
    } else {
      data.admin_user_id = editId;
      res = await editAdminUser(data);
    }

    if (res.code === 200) {
      message.success(res.msg);
      actionRef.current.reload();
      isShowModal(false);
    }
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/19 16:07:41
   * 功能：头像配置
   */
  const avatarProps = {
    name: 'avatar_file',
    action: '/admin/AdminUser/avatar',
    headers: {
      AdminToken: localStorage.getItem('access_token') || '',
    },
    accept: '.jpg,.png,.jpeg',
    data: {
      admin_user_id: editId,
    },
    showUploadList: false,
    beforeUpload(file) {
      if (file.size > 102400) {
        message.warning('图片不可大于100k~');
        return false;
      }
    },
    onChange(info) {
      if (info.file.status === 'done') {
        let res = info.file.response;
        if (res.code == 200) {
          message.success('头像上传成功~');
          setAvatar(res.data.avatar);
          actionRef.current.reload();
        } else {
          message.error(res.msg);
        }
      } else if (info.file.status === 'error') {
        message.error('头像上传失败！');
      }
    },
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/19 16:13:31
   * 功能：头像组件
   */
  function avatarPro() {
    return (
      <Form.Item label="头像">
        <div className={styles.editAvatar}>
          <Avatar
            size={110}
            icon={<UserOutlined/>}
            src={avatar}
            onClick={() => setVisible(true)}
          />

          <Image
            width={200}
            style={{display: 'none'}}
            preview={{
              visible,
              src: avatar,
              onVisibleChange: (value) => {
                setVisible(value);
              },
            }}
          />

          <Upload {...avatarProps}>
            <Button className={styles.btnUpload} icon={<UploadOutlined/>}>
              更换头像
            </Button>
          </Upload>

          <span className={styles.desc}>jpg、png图片，小于100KB，宽高1:1</span>
        </div>
      </Form.Item>
    );
  }

  function handleChange(value) {
    console.log(`selected ${value}`);
  }

  return (
    <Modal
      title={title}
      visible={isModalVisible}
      onCancel={() => isShowModal(false)}
      footer={null}
      destroyOnClose={true}
    >
      <ProForm
        onFinish={(values) => handleSubmit(values)}
        request={
          editId == null
            ? () => {
              return {sort: 50};
            }
            : () => getData()
        }
        {...formItemLayout}
        layout={formLayout}
      >
        {editId === null ? '' : avatarPro()}
        <ProFormText
          name="username"
          label="账号"
          placeholder="请输入账号"
          rules={[{required: true, message: '账号不能为空'}]}
        />
        <ProFormText
          name="nickname"
          label="昵称"
          placeholder="请输入昵称"
          rules={[{required: true, message: '昵称不能为空'}]}
        />
        {editId === null ? (
          <ProFormText.Password
            name="password"
            label="密码"
            placeholder="请输入密码"
            rules={[
              {required: true, message: '密码不能为空'},
              {type: 'string', min: 6, message: '密码最小6位'},
            ]}
          />
        ) : (
          ''
        )}

        <Form.Item
          name="admin_role_ids"
          label="角色"
          rules={[
            {required: true, message: '角色不能为空'},
          ]}
        >
          <Select
            mode="multiple"
            allowClear
            style={{width: '100%'}}
            placeholder="请选择角色"
            onChange={handleChange}
          >
            {
              roleList.map((item, index) => {
                return (
                  <Option key={item.admin_role_id} value={item.admin_role_id}>{item.role_name}</Option>
                )
              })
            }
          </Select>
        </Form.Item>
        <Form.Item
          name="phone"
          label="手机"
          rules={[
            {
              message: '请输入正确的手机号',
              pattern: /^1[3456789]\d{9}$/,
            },
          ]}
        >
          <Input placeholder="请输入手机" maxLength={11}/>
        </Form.Item>
        <ProFormText
          name="email"
          label="邮箱"
          placeholder="请输入邮箱"
          rules={[
            {type: 'email', message: '邮箱格式不对'},
          ]}
        />
        <ProFormTextArea name="remark" label="备注" placeholder="请输入备注"/>
        <ProFormText name="sort" label="排序" placeholder="请输入排序"/>
      </ProForm>
    </Modal>
  );
};

export default Edit;
